﻿using Sample.Interfaces;
using System;
using System.Threading.Tasks;

namespace Client
{
    class Program
    {
        static void Main(string[] args)
        {
            var runTask = Run(args);

            Task.WaitAll(runTask);
        }

        static async Task<Task> Run(string[] args)
        {
            Console.WriteLine("Hello World!");

            var context = new OrleansClientBuilderContext
            {
                ClusterId = "dev",
                ServiceId = "sample",
                ZookeeperConnectionString = "127.0.0.1:2181,127.0.0.1:2183,127.0.0.1:2183"
            };

            var hClient = new OrleansClientHelper(context);

            //using (var client = await hClient.StartConnectAsync())
            {
                //Console.WriteLine("\nService connect success.\n");

                //var iUserService = client.GetGrain<IUserService>(primaryKey: 0);

                //var result = await iUserService.Exist("18217063631");
                //Console.WriteLine("{0} result", result);

                //Console.WriteLine("0. state:{0}", iUserService.GetState().Result);

                Parallel.For(0,3, async index => {
                    using (var client = await hClient.StartConnectAsync())
                    {
                        var iUserService = client.GetGrain<IUserService>(primaryKey: 23);
                        Console.WriteLine("A 0. state:{0}", iUserService.GetState().Result);
                        await dowork(iUserService);
                        Console.WriteLine("A 1. money:{0}", iUserService.GetMoney().Result);
                    }
                });

                Console.WriteLine("task B:");

                Parallel.For(0, 3, async index => {
                    using (var client = await hClient.StartConnectAsync())
                    {
                        var iUserService = client.GetGrain<IUserService>(primaryKey: 49);
                        Console.WriteLine("B 0. state:{0}", iUserService.GetState().Result);
                        await dowork(iUserService);
                        Console.WriteLine("B 1. money:{0}", iUserService.GetMoney().Result);
                    }
                });



                //await dowork(iUserService);
                //Console.WriteLine("1. money:{0}", iUserService.GetMoney().Result);


                //iUserService = client.GetGrain<IUserService>(primaryKey: 1);
                //await dowork(iUserService);
                //Console.WriteLine("2. money:{0}", iUserService.GetMoney().Result);

                Console.ReadLine();

            }

            return Task.CompletedTask;
        }

        static async Task dowork(IUserService service)
        {
            Parallel.For(0, 100, async a =>
            {
               await service.AddMoney();
            });
        }

    }
}
